package com.cedric.yixianpai.server.service.serviceImpl;

import com.cedric.yixianpai.game.Duel;
import com.cedric.yixianpai.server.Utils.GameInfoDTO;
import com.cedric.yixianpai.server.Utils.*;
import com.cedric.yixianpai.server.service.CardGameService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

@Service
public class CardGameServiceImpl implements CardGameService {

    public GameResult startGame(GameInfoDTO gameInfoDTO) {
        Duel duel;
        try {
            duel = new Duel(gameInfoDTO);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        return duel.startFight();
    }
//
//    public BestResult findBest(GameInfoDTO gameInfoDTO) {
//        //fixme：提前预警拦截器
//        if(gameInfoDTO.getP1Cards().size()>5){
//            return null;
//        }
//        Set<List<CardVo>> permutations = new HashSet<>();
//        permutation(gameInfoDTO.getP1Cards(), permutations, 0);
//        BestResult bestResult = new BestResult();
//
//        ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//
//        List<Callable<Void>> tasks = new ArrayList<>(); // 存储任务以便后续提交
//        //todo:实现多线程熔断机制
//        for (List<CardVo> cardList : permutations) {
//            tasks.add(() -> {
//                GameInfoDTO gInfo = new GameInfoDTO(gameInfoDTO, cardList);
//                try {
//                    GameResult gameRes=new Duel(gInfo).startFight();
//                    if (gameRes.getWinner().equals(gameInfoDTO.getP1InfoDTO().getName())) {
////                        System.out.println(Thread.currentThread());
//                        synchronized (bestResult) { // 确保线程安全地修改 results
//                            bestResult.addWin(gameRes, cardList);
//                        }
//                    }
//                } catch (NoSuchMethodException e) {
//                    throw new RuntimeException(e);
//                }
//                return null;
//            });
//        }
//
//        try {
//            List<Future<Void>> futures = executor.invokeAll(tasks); // 提交所有任务并等待完成
//            for (Future<Void> future : futures) {
//                try {
//                    future.get(); // 等待任务完成
//                } catch (CancellationException | ExecutionException e) {
//                    // 任务被取消，不需要处理
//                }
//            }
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } finally {
//            executor.shutdown();
//        }
//        return bestResult;
//    }

    /*未使用线程池*/
    public BestResult findBest(GameInfoDTO gameInfo) {
        BestResult bestResult =new BestResult();
        Set<List<CardVo>> permutations = new HashSet<>();
        permutation(gameInfo.getP1Cards(), permutations, 0);
       try{ for (List<CardVo> cardList : permutations) {
            GameInfoDTO gInfo = new GameInfoDTO(gameInfo, cardList);
            GameResult gameRes= new Duel(gInfo).startFight();
            if (gameRes.getWinner().equals(gameInfo.getP1InfoDTO().getName())) {
               bestResult.addWin(gameRes, cardList);
                }
        }}catch (NoSuchMethodException e){
           e.printStackTrace();
       }
        return bestResult;
    }

    public List<CardInfoDTO> getCards() {
        CardFactory cardFactory = new CardFactory();
        return cardFactory.getCards();
    }

    private void permutation(List<CardVo> cardVos, Set<List<CardVo>> result, int start) {
        if (start == cardVos.size() - 1) {
//            for (CardVo vo : cardVos) {
//                System.out.println(vo.getLvl());
//            }
            //实现深拷贝
            List<CardVo> deepCopiedList = new ArrayList<>();
            for (CardVo cardVo : cardVos) {
                try {
                    CardVo clonedCardVo = (CardVo) cardVo.clone();
                    deepCopiedList.add(clonedCardVo);
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
            }
            result.add(deepCopiedList);
        } else {
            for (int i = start; i < cardVos.size(); i++) {
                swap(cardVos, start, i);
                permutation(cardVos, result, start + 1);
                swap(cardVos, start, i);
            }
        }
    }

    private static void swap(List<CardVo> cards, int a, int b) {
        CardVo temp = cards.get(a);
        cards.set(a, cards.get(b));
        cards.set(b, temp);
    }

}
